var WP_RESTFUL_URL = 'http://192.168.3.105:8080/API/';
var WP_RESTFUL_TYPE = 'json';

var BUILDER_RESTFUL_URL = 'https://mwpsi.cognizant.com/builderscrum/';

var WP_LOGIN_USERVALID = "Valid user";
var WP_LOGIN_ERR = "We were unable to match the User ID and password you entered. Please check your entries and try again.";

var WP_USER_ID = 1;
var WP_USER_NAME = '', WP_WORK_MAIL = '', WP_MAIL_TYPE = '';
var WP_USER_LIST = [];
var WP_COMMUNITY_LIST = [];
var WP_NETWORK_USERS = [];
var WP_MENTION_COMM = [];
var WP_404_ERR = 'net work error';
var BOXURL = "https://api.box.com/oauth2/authorize?response_type=code&client_id=sldbzs4y3zqtnap6k8qvgmcfex6m08xf&state=authenticated&redirect_uri=https://mwpsi.cognizant.com/WPScrumui/";
var intranetUrl = 'http://www.jabil.com';
var loginUrl = '';
var Screen = {};
var WP_HEADER, WP_BODY;
var WP_MESSAGE = {};
var WP_APP_LOADED = 0;
var WP_TIMEOUT_MESSAGE = 'This service is currently unavailable. Please close your browser and reopen myJabil to access your productivity tools. If the problem persists, please enter a service request in ServiceNow.';

var CLIENT_ID = '488855778577-598h7ajl6fatldci40upf35mqck58f5j.apps.googleusercontent.com',
    API_KEY = 'AIzaSyBx-5j0qwSkE5Fz-owOBCKJblVvOk4CYXs',
    SCOPES = [
        'https://mail.google.com/',
        'https://www.googleapis.com/auth/gmail.compose',
        'https://www.googleapis.com/auth/gmail.modify',
        'https://www.googleapis.com/auth/gmail.labels',
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/plus.me',
        'https://www.google.com/m8/feeds',
        'https://www.googleapis.com/auth/contacts.readonly'
    ];
var GMAIL_SYNC_INTERVAL = 3 * 60 * 1000;
var DRIVE_SYNC_INTERVAL = 3 * 60 * 1000;
var LAYOUT_ITEM_CONFIG = {
    'DEFAULT': {imgCSS: {'display': 'none'}},
    'smartsteam': {textCSS: {'color': 'black'}, imgCSS: {'display': 'none'}},
    'boxes': {textCSS: {color: 'black'}, imgCSS: {'display': 'none'}},
    'iwanto':{textCSS: {color: 'black'}, imgCSS: {'display': 'none'}},
    'contacts':{textCSS: {color: 'black'}, imgCSS: {'display': 'none'}},
    'apptools':{textCSS: {color: 'black'}, imgCSS: {'display': 'none'}}
};

var WP_PROFILE_IS_EDIT = true;
var WP_ADD_TAG_IS_ADD = true;
var MAX_MAIL_ACCOUNT = 2000;

var WP_APP_CONFIG = {
    app: {
        root: './',
        html: 'html/',
        'default': [],
        templates: [{
            html: 'homepage.profile.tmpl.html',
            id: 'wp_homepage_profile'
        }, {
            html: 'homepage.search.tmpl.html',
            id: 'wp_homepage_search'
        }, {
            html: 'homepage.notifactions.tmpl.html',
            id: 'wp_homepage_notifactions'
        }, {
            html: 'iframe.window.html',
            id: 'wp_iframe_pop_win'
        }, {
            html: 'all.liked.users.list.win.tmpl.html',
            id: 'wp_all_like_users_list'
        }]
    },
    modules: {
        iwantto: {
            name: 'I Want To',
            panel: 'iwanto',
            style: {
                'background-color': '#dddddd'
            },
            templates: [{
                html: 'iwantto.tmpl.html',
                id: 'wp_homepage_iwantto'
            }],
            require: []
        },
        smartstream: {
            name: 'Smart Stream',
            panel: 'smartsteam',
            style: {},
            templates: [{
                html: 'smartstream.tmpl.new.html',
                id: 'wp_homepage_smartstream'
            }, {
                html: 'smartstream.topic.detail.tmpl.html',
                id: 'wp_homepage_smartstream_detail'
            }/*, {
				html: 'smartstream.share.tmpl.html',
                id: 'wp_homepage_smartstream_share'
            }, {
                html: 'smartstream.share.email.tmpl.html',
                id: 'share_email_win'
            }, {
                html: 'community.viewall.tmpl.html',
                id: 'wp_homepage_community_smartstream_viewall'
            }*/],
            require: [
                'iframe.window.html', 'all.liked.users.list.win.tmpl.html'
            ]
        },
        contacts: {
            name: 'Contacts',
            panel: 'contacts',
            style: {
                'background-color': '#ededed'
            },
            templates: [{
                html: 'contacts.main.tmpl.html',
                id: 'wp_contacts_main'
            }, {
                html: 'contacts.add.tmpl.html',
                id: 'wp_contacts_add'
            }],
            require: ['']
        },
        apptools: {
            name: 'App Tools',
            panel: 'apptools',
            style: {
                'background-color': '#ededed'
            },
            templates: [{
                html: 'apps.tools.tmpl.html',
                id: 'wp_apps_tools'
            }, {
                html: 'applications.add.detail.tmpl.html',
                id: 'wp_apps_add_detail'
            }/*,{
                html: 'apps.tools.register.tmpl.html',
                id: 'wp_apps_tools_register'
            }, {
                html: 'apps.tools.register.editlist_tmpl.html',
                id: 'wp_apps_tools_register_editlist'
            }, {
                html: 'applications.tools.create.tmpl.html',
                id: 'wp_apps_tools_create'
            }, {
                html: 'app.edit.list.tmpl.html',
                id: 'wp_app_edit'
            } */],
            require: ['']
        },
        communities: {
            name: 'Communities',
            panel: 'communities',
            style: {
                'background-color': '#ECB244'
            },
            templates: [{
                html: 'communities.profile.tmpl.html',
                id: 'wp_communities_profile_win'
            }, {
                html: 'communities.tmpl.html',
                id: 'wp_communities_win'
            }, {
                html: 'communities.nominate.experts.html',
                id: 'wp_communities_nominate_experts_win'
            }, {
                html: 'communities.create.tmpl.html',
                id: 'wp_communities_create'
            }],
            require: ['iframe.window.html']
        },
        documents: {
            name: 'Documents',
            panel: 'documents',
            style: {
                'background-color': '#E6E6E6'
            },
            templates: [{
                html: 'documents.tmpl.html',
                id: 'wp_homepage_documents'
            }],
            require: ['']
        },
        inbox: {
            name: 'Inbox',
            panel: 'inbox',
            style: {
                'background-color': '#006DA5'
            },
            templates: [{
                html: 'inbox.tmpl.html',
                id: 'wp_inbox_win'
            }],
            require: ['']
        },
        boxs: {
            name: 'Boxs',
            panel: 'boxes',
            style: {
                'background-color': '#f2f2f2'
            },
            templates: [{
                html: 'boxes.tmpl.html',
                id: 'wp_box_win'
            }],
            require: ['']
        },
        gmail: {
            name: 'Gmail',
            panel: 'gmail',
            style: {},
            templates: [{
                html: 'gmail.tmpl.html',
                id: 'wp_gmail_win'
            }],
            require: ['']
        },
        calendar: {
            name: 'Calendar',
            panel: 'calendar',
            style: {
                'background-color': '#FFFFFF'
            },
            templates: [{
                html: 'calendar.tmpl.html',
                id: 'wp_calendar'
            }],
            require: ['']
        },
        drive: {
            name: 'Drive',
            panel: 'drive',
            style: {
                'background-color': '#ededed'
            },
            templates: [{
                html: 'drive.tmpl.html',
                id: 'wp_drive'
            }],
            require: ['']
        },
        intranet: {
            name: 'Intranet',
            panel: 'intranet',
            style: {
                'background-color': '#f2f2f2'
            },
            templates: [{
                html: 'intranet.html',
                id: 'wp_intranet'
            }],
            require: ['']
        }
    }
};

var WPMoudleManager = (function () {
    var debug = false,
        templates = '',
        modules = {},
        stringModules = '',
        app = WP_APP_CONFIG.app,
        userModules = [];

    return {
        getModule: function (moduleName) {
            if (!this.haveModule(moduleName))
                return false
            return modules[moduleName];
        },
        putModules: function (modules) {
            userModules = modules;
            stringModules = userModules.join(';');
        },
        checkModule: function (moduleName) {
            if (this.haveModule(moduleName))
                return true;
            alert(moduleName + ' unload.');
            return false;
        },
        haveModule: function (moduleName) {
            return (stringModules.indexOf(moduleName) > -1);
        },
        loadTemplate: function (template) {
            if (templates.indexOf(template.html) > -1) {
                return;
            }
            templates += template.html;
            Workport.utils.loadPage(app.root + app.html + template.html, template.id);
        },
        loadModule: function (moduleName, index) {
            if (this.haveModule(moduleName) && !WP_APP_CONFIG.modules.hasOwnProperty(moduleName)) {
                return;
            }
            modules[moduleName] = WP_APP_CONFIG.modules[moduleName];
            modules[moduleName].index = index;
            var item = $('<div class="item" id="' + WP_APP_CONFIG.modules[moduleName].panel + '"></div>').css(WP_APP_CONFIG.modules[moduleName].style);
            $('#body_layout').append(item);
            for (var i = 0, l = WP_APP_CONFIG.modules[moduleName].templates.length; i < l; i++) {
                this.loadTemplate(WP_APP_CONFIG.modules[moduleName].templates[i]);
            }
        },
        initApp: function () {
            if(['IE 6','IE 7','IE 8','IE 9'].indexOf(Workport.getBrowser()) > -1){
                location = location.protocol + '//' + location.host + location.pathname + 'ErrorPages/404.html';
            }
            console.log('init wp app');

            Workport.utils.loadPage('html/header.tmpl.html', 'wp_header');
            
            var div = document.createElement('div');
            div.id = 'wp_body';
            document.body.appendChild(div);
            var self = this;

            $(div).load('html/homepage.tmpl.html', function (data) {
                Workport.utils.clearCount();

                var parseURL = Workport.LocationManager.parseURL();
                Workport.utils.startCount(function (page) {
                    Workport.LocationManager.execute(parseURL);
                });

                var interval = setInterval(function () {
                    if (WP_MAIL_TYPE != '') {
                        clearInterval(interval);
                        if (WP_MAIL_TYPE.toLocaleLowerCase() == 'gmail') {
                            if(USER_DIY.indexOf('inbox') > -1)
                                USER_DIY.splice(USER_DIY.indexOf('inbox'), 1);
                        } else if (WP_MAIL_TYPE.toLocaleLowerCase() == 'outlook'){
                            if(USER_DIY.indexOf('calendar') > -1)
                                USER_DIY.splice(USER_DIY.indexOf('calendar'), 1);
                            if(USER_DIY.indexOf('gmail') > -1)
                                USER_DIY.splice(USER_DIY.indexOf('gmail'), 1);
                        }
                        self.putModules(USER_DIY);
                        for (var i = 0, l = WP_APP_CONFIG.app.templates.length; i < l; i++) {
                            self.loadTemplate(app.templates[i]);
                        }

                        for (var i = 0, l = userModules.length; i < l; i++) {
                            self.loadModule(userModules[i], i);
                        }

                        $('#body_layout').find('.item').each(function (){
                            var self = $(this);
                            var loader = new Workport.Loader(self, LAYOUT_ITEM_CONFIG[self.prop('id')] || LAYOUT_ITEM_CONFIG.DEFAULT);
                            loader.show();
                            $(this).css({
                                width: 256,
                                height: '100%' //Screen.bodyHeight
                            });
                        });
                        HomePage_Scrollable.reset();
                        HomePage_Scrollable.scroll(".item", wp_main);
                    }
                }, 100);

                $(document).off('contextmenu');
                document.oncontextmenu = null;
            });
        }
    }
})();

function setAppCount() {
    WP_APP_LOADED++;
    //    if(6 == WP_APP_LOADED){
    //         $('#global_wait').hide();
    //    }
}

$(document).keydown(function (event) {
    if ((event.altKey) && ((event.keyCode == 37) || (event.keyCode == 39))) {
        event.returnValue = false;
        return false;
    }
    if (event.keyCode == 116) {
        return false;
    }
    if ((event.ctrlKey) && (event.keyCode == 82)) {
        return false;
    }
});

$(document).bind("contextmenu", function () {
    return false;
});

var Workport = Workport || {};
Workport.WP_RESTFUL_URL = '/API/';

Workport.utils = (function () {
    function _getDocHeight() {
        var doc = document;
        return Math.max(
            Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
            Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
            Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
        );
    }

    function _wp_invoker() {
        var url = window.location.href;
        var params = url.substr(url.indexOf('=') + 1).split('|');
        $('#' + params.shift()).trigger('wp_invoker', [params]);

    }

    function _getViewPort() {
        var e = window,
            a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return {
            width: e[a + 'Width'],
            height: e[a + 'Height']
        };
    }

    function _obj2url(url, obj) {
        var s = '';
        for (var k in obj)
            s += (s === '' ? '?' : '&') + k + '=' + obj[k];
        return url + s;
    }

    var startCallback = function () {},
        isDebug = false;

    function _clearCount() {
        if (isDebug) console.debug('Clear Count');
        startCallback = function () {
        };
    }

    function _startCount(callback) {
        if (isDebug) console.debug('Start Count');
        startCallback = callback || function () {
        };
    }

    function _endCount() {
        if (isDebug) console.debug('End Count');
    }

    function _loadPage(page, id) {
        if (isDebug) console.debug('start load page' + page);
        var div = document.createElement('div');
        div.id = id;
        document.body.appendChild(div);
        $(div).load(page, function () {
            if (isDebug) {
                console.debug(page + ' load success');
            }
            startCallback(page);
        });
    }

    /**
     sTitle:
     sMsg:
     sBtnTxt:
     sType: yesno
     fCall: function
     actions:[
     {name:'yes',class:'btn yes', css:{}, action:function(e){}},
     {name:'no',class:'btn no', css:{}, action:function(e){}}
     ]
     **/
    function _alertMsg(sTitle, sMsg, sBtnTxt, sType, fCall) {
        var windom = $('#global_alert_win');
        windom.css('padding', '10px');
        var win = $('#global_alert_win').data('kendoWindow');
        var btnYes = $('.yes', '#global_alert_win');
        var btnNo = $('.no', '#global_alert_win');
        var winMsg = $('p', '#global_alert_win');
        var callArguments = arguments;
        windom.find('button').off().remove();
        btnNo.text('Cancel');

        if (!win) {
            $("#global_alert_win").kendoWindow({
                width: 600,
                minHeight: 60,
                draggable: false,
                resizable: false,
                modal: true,
                actions: ["Close"]
            });
            win = $('#global_alert_win').data('kendoWindow');
            $($("#global_alert_win_wnd_title").next().find("span.k-i-close")).attr("id", "global_alert_win_close_icon_span");
            $($("#global_alert_win").find("span.btn.yes")).attr("id", "global_alert_win_yes_btn_span");
        }
        btnYes.unbind();
        btnYes.bind({
            click: function () {
                callArguments[callArguments.length - 1](true);
                win.close();
            }
        });
        btnNo.unbind();
        btnNo.bind({
            click: function () {
                callArguments[callArguments.length - 1](false);
                win.close();
            }
        });

        if (arguments.length == 3) {
            btnNo.hide();
            btnYes.text('OK').show();
            if (sBtnTxt instanceof Array && sBtnTxt.length > 1) {
                btnYes.hide();
                var button, bdata, cur;
                for (var i = 0, l = sBtnTxt.length; i < l; i++) {
                    cur = $.extend({
                        'name': 'Ok',
                        'class': 'btn no',
                        'css': {},
                        action: function () {
                        }
                    }, sBtnTxt[i]);
                    button = $('<button type="button" class="tempbutton" style="min-width: 30px; margin:0 5px; border: 0;"></button>');
                    button.addClass(cur['class']).css(cur.css);
                    button.data('bdata', cur);
                    button.text(cur.name);
                    button.click(function (e) {
                        bdata = $(this).data('bdata');
                        if (typeof bdata.action == 'function') {
                            bdata.action(e);
                        }
                        win.close();
                    });
                    windom.append(button);
                }
            }
        } else {
            btnNo.show();
            btnYes.text(sBtnTxt);
        }
        win.center();
        win.title(sTitle);
        if(sMsg){
            winMsg.html(sMsg);
        }
        else
            winMsg.text(sMsg);
        win.center();
        win.open();
    }

    function _getRealLength(data) {
        if (data) {
            var real = data.replace(new RegExp("&nbsp;", "gim"), " ");
            real = real.replace(new RegExp("<[^>]+>", "gim"), "");
            real = real.replace(new RegExp("&[^;]+;", "gim"), "#");
            var empty = real.replace(new RegExp(" ", "gim"), "");
            if (empty.length == 0)
                return 0;
            else
                return real.length;
        } else {
            return 0;
        }
    }

    function _getRealContent(data) {
        if (data) {
            var real = data.replace(new RegExp("&nbsp;", "gim"), " ");
            return real;
        } else {
            return "";
        }
    }

    function _getDateDiff(startTime, endTime, diffType) {
        diffType = diffType.toLowerCase();
        var divNum = 1;
        switch (diffType) {
            case "second":
                divNum = 1000;
                break;
            case "minute":
                divNum = 1000 * 60;
                break;
            case "hour":
                divNum = 1000 * 3600;
                break;
            case "day":
                divNum = 1000 * 3600 * 24;
                break;
            default:
                break;
        }
        return parseInt(Math.abs((endTime.getTime() - startTime.getTime()) / parseInt(divNum)));
    }

    function _calDays(CreatedDate, ServerDate) {
        var dtCreatedDate = new Date(CreatedDate);
        var dtServerDate = new Date(ServerDate);
        var iDay = _getDateDiff(dtServerDate, dtCreatedDate, "day");
        var iHour;
        var iMinutes;
        var iSeconds;

        if (iDay == 0) {
            iHour = _getDateDiff(dtServerDate, dtCreatedDate, "hour");
            if (iHour == 0) {

                iMinutes = _getDateDiff(dtServerDate, dtCreatedDate, "minute");
                if (iMinutes == 0) {
                    iSeconds = _getDateDiff(dtServerDate, dtCreatedDate, "second");
                    if (iSeconds < 1) iSeconds = 1;
                    return iSeconds + " sec(s) ago";
                } else {

                    return iMinutes + " min(s) ago";
                }
            } else {
                return iHour + " hr(s) ago";
            }
        } else {
            return iDay + " day(s) ago";
        }
        return "a days ago";
    }

    function _encodeHtml(s) {
        REGX_HTML_ENCODE = /"|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g;
        return (typeof s != "string") ? s :
            s.replace(REGX_HTML_ENCODE,
                function ($0) {
                    var c = $0.charCodeAt(0),
                        r = ["&#"];
                    c = (c == 0x20) ? 0xA0 : c;
                    r.push(c);
                    r.push(";");
                    return r.join("");
                });
    };

    function _showTooltip(errMsg, elem, location) {
        var _location = "right";
        if (location) {
            _location = location;
        };
        elem.kendoTooltip({
            content: errMsg,
            position: _location,
            hide: function () {
                elem.data('kendoTooltip').destroy();
            }
        });
        elem.data('kendoTooltip').show();
    }

    return {
        getDocHeight: _getDocHeight,
        getViewPort: _getViewPort,
        obj2url: _obj2url,
        clearCount: _clearCount,
        startCount: _startCount,
        endCount: _endCount,
        loadPage: _loadPage,
        wp_invoker: _wp_invoker,
        alertMsg: _alertMsg,
        getRealLength: _getRealLength,
        getRealContent: _getRealContent,
        calDays: function (CreatedDate, ServerDate) {
            return _calDays(CreatedDate, ServerDate);
        },
        encodeHtml: _encodeHtml,
        showTooltip: _showTooltip
    };
})();

Workport.Communication = (function () {
    var wpToken = '', gmailFirstVisit = true, driveFirstVisit = true, calendarFirstVisit = true;
        
    function request(url, method, callback, sync, data) {
        var p = {
            url: WP_RESTFUL_URL + url,
            type: method,
            cache: false,
            async: !sync,
            dataType: 'json',
            headers: {
                'X-WP-Token': wpToken
            },
            error: function (r, t, e) {
                alert(WP_404_ERR);
                callback(r.status);
            },
            success: function (d, t, r) {
                callback(r.status, d);
            }
        };

        if (data || false) {
            p.contentType = 'application/json';
            p.data = data;
        }
        return $.ajax(p);
    }

    function batchRequest(r, s, f) {
        /** r = [{url:, method:, data:}, ...] */
        r = r || [];
        var i, l = r.length,
            t = "";
        if (l > 0) {
            for (i = 0; i < l; i++) {
                if (t != "") t += ",";
                t += "$.ajax({cache:false,dataType:'json',headers:{'X-WP-Token':'" + wpToken + "'},";
                t += "url:'" + WP_RESTFUL_URL + "'+r[" + i + "].url,";
                t += "type:r[" + i + "].method";
                if (r[i].data || false) {
                    t += ",contentType:'application/json',";
                    t += "data:JSON.stringify(r[" + i + "].data)";
                }
                t += "})";
            }

            s = s || function () {
            };
            f = f || function () {
            };
            (new Function("r", "s", "f", "$.when(" + t + ").then(s, f);"))(r, s, f);
        }
    }

    return {
        setToken: function (token) {
            wpToken = token;
        },
        get: function (url, callback) {
            return request(url, 'get', callback, false);
        },
        syncGet: function (url, callback) {
            return request(url, 'get', callback, true);
        },
        post: function (url, callback, data) {
            return request(url, 'post', callback, false, JSON.stringify(data));
        },
        syncPost: function (url, callback, data) {
            return request(url, 'post', callback, true, JSON.stringify(data));
        },
        put: function (url, callback, data) {
            return request(url, 'put', callback, false, JSON.stringify(data));
        },
        syncPut: function (url, callback, data) {
            return request(url, 'put', callback, true, JSON.stringify(data));
        },
        del: function (url, callback) {
            return request(url, 'delete', callback, false);
        },
        syncDel: function (url, callback) {
            return request(url, 'delete', callback, true);
        },
        batch: batchRequest,
        sendReport:function(modulename) {
            var flag = false;
            if (modulename == "Gmail") {
                if (gmailFirstVisit) {
                    flag = true;
                    gmailFirstVisit = false;
                }
            }      
            if (modulename == "GDrive") {
                if (driveFirstVisit) {
                    flag = true;
                    driveFirstVisit = false;
                }
            } 
            if (modulename == "GCalendar") {
                if (calendarFirstVisit) {
                    flag = true;
                    calendarFirstVisit = false;
                }
            } 
            if (flag) {
                return $.post('https://mwpsi.cognizant.com/API/Report/' + modulename);
            }
        }
    };
}());

var Letter = function (elem, f, color) {
    var _elemName = $(elem).attr("data-alpa-name");

    var _characters = ['All', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'];
    var _elem = $(elem);
    var _offset = _elem.offset();
    var _left = _offset.left + _elem.width() / 2 - 25;
    var _top = _offset.top + _elem.height() / 2 - 25 - 200;
    var _elemHeight = Math.floor(_elem.height() / _characters.length);
    var _html = '<ul id="' + _elemName + '_letter" class="letter_filter" style="height:476px;">';
    var _oldClickElem;
    var hightLightColor = "#a6a6a6";
    if (color) {
        hightLightColor = color;
    }
    $.map(_characters, function (_character) {
        _html += '<li id=' + _elemName + "_" + _character + ' style="height:' + _elemHeight + 'px;line-height:' + _elemHeight + 'px;">' + _character + '</li>';
    });
    _html += '</ul>';
    _html += '<div class="imgwrapper" style="position:absolute;top:' + _top + 'px;left:' + _left + 'px;width:50px;height:50px;background-color:#5A5A5A;color:white;text-align:center;line-height:50px;display:none;font-size:40px;"></div>';
    _html = $(_html);

    _html.appendTo(_elem);
    $('li', _html).on({
        click: function () {
            var _letter = $(this).text();
            if (_oldClickElem) {
                _oldClickElem.css('background-color', '');
            }
            $(this).css('background-color', hightLightColor);
            _oldClickElem = $(this);

            var _curren = _elem.find(".imgwrapper");
            _curren.show();
            f(_letter);
            $(_curren).text(_letter);
            $(_curren).fadeOut('slow', function () {
                _curren.hide();
            });
        }
    });
    return {
        update: function () {
            var _n = $(elem);
            var _l = _n.width() / 2 - 25,
                _t = _n.offset().top + _n.height() / 2 - 25 - 200;
            $(_html[1]).css({
                'left': _l + 'px',
                'top': _t + 'px'
            });
        },
        cancleHighLight: function () {
            if (_oldClickElem) {
                _oldClickElem.css('background-color', '');
            }
        }
    }
};

Workport.AtWho = (function () {
    var def_config = {
            at: "@",
            searchKey: "UserName",
            startWithSpace: false,
            highlightFirst: true,
            displayTpl: "<li><img src=\"${UserImageURL}\" onerror=\"this.setAttribute('src','imgs/20x20.png');\"/><div>&nbsp;${UserName}</div></li>"
        },
        dataType = {
            'U': function () {
                return WP_NETWORK_USERS;
            },
            'C': function () {
                return WP_MENTION_COMM;
            }
        },
        sign = 'workport-atwho',
        configes = {
            'U': {
                insertTpl: "<a href='#' class='" + sign + "' id=\"${UserID}\" name=\"homepageProfileWin.user_info_win_create('${UserID}');\">${atwho-at}${UserName}</a>"
            },
            'C': {
                insertTpl: "<a href='#' class='" + sign + "' id=\"${UserID}\" name=\"community_profile_controller.initProfilePage('${UserID}');\">${atwho-at}${UserName}</a>"
            }
        },
        isDebug = false;

    return {
        getAtIds: function (html) {
            var arr = [];
            $(html).find('.' + sign).each(function () {
                arr.push(this.getAttribute('id'));
            });
            return arr.join(';');
        },
        parse: function (space) {
            $(space).on('click', '.' + sign, function (e) {
                e.preventDefault();
                jQuery.globalEval(this.getAttribute('name'));
                e.stopPropagation();
            });
        },
        at: function (target, config) {
            return $(target).atowho(config);
        },
        atKendoEditor: function (kendoEditor, type) {
            if (isDebug) console.dir(dataType[type.toUpperCase()]());
            if (!$(kendoEditor.body).data('hasat')) {
                $(kendoEditor.body).atwho('destroy');
            }
            var ifr = kendoEditor.wrapper.find('iframe'),
                cont = ifr.contents();
            cont.find('body').off('keydown');
            $(kendoEditor.body).data('hasat', 1);
            var conf = $.extend({}, def_config, configes[type.toUpperCase()], {
                data: dataType[type.toUpperCase()]()
            });
            if (isDebug) console.dir(conf);
            return $(kendoEditor.body).atwho('setIframe', kendoEditor.wrapper.find('iframe')[0]).atwho(conf);
        }
    }
}());

Workport.AtWho.parse(document);

Workport.LocationManager = (function () {
    var isDebug = false,
        URList = {
            emptyFunction: function () {
                if (isDebug) console.log('call empty function');
            }
        },
        isexed = false,
        LINK = "&&",
        JOIN = "==:",
        BREAK = "?URL:";

    return {
        getURLParameter: function (url) {
            var aQuery = (url || window.location.href)['split'](BREAK);
            var aGET = {};
            if (aQuery.length > 1) {
                var aBuf = aQuery[1].split(LINK);
                for (var i = 0, iLoop = aBuf.length; i < iLoop; i++) {
                    var aTmp = aBuf[i].split(JOIN);
                    aGET[aTmp[0]] = aTmp[1];
                }
            }
            if (isDebug) console.log(aGET);
            return aGET;
        },
        addURL: function (windowName, handler) {
            URList[windowName] = handler;
        },
        parseURL: function (url) {
            var geter = this.getURLParameter(url);
            if (geter['windowName'] || geter['params']) {
                return {
                    windowName: decodeURIComponent(geter['windowName']),
                    params: JSON.parse(decodeURIComponent(geter['params']))
                };
            }
            return {
                windowName: 'emptyFunction',
                params: {}
            };
        },
        serializeURL: function (windowName, params) {
            var url = this.getRoot() + BREAK + 'windowName' + JOIN + encodeURIComponent(windowName) + LINK + 'params' + JOIN + encodeURIComponent(JSON.stringify(params));
            if (isDebug) {
                console.log(url);
            }
            return url;
        },
        getRoot: function () {
            return location.protocol + '//' + location.host + location.pathname;
        },
        setFullURL: function (kendoWindow, windowName, params) {
            var ser = Workport.LocationManager.serializeURL(windowName, params);
            Workport.Clipboard.setCopyURL(kendoWindow, ser);
            return ser;
        },
        execute: function (urlobj) {
            urlobj = urlobj || URList.emptyFunction;
            if (isDebug) {
                console.log(urlobj);
                console.log(URList);
            }
            if (URList[urlobj.windowName] && !isexed) {
                URList[urlobj.windowName](this.parseURL().params);
                if (urlobj.windowName != 'emptyFunction') {
                    isexed = true;
                }
            }
        }
    }
}());

$(function () {
    Workport.Clipboard = (function () {
        var client = new ZeroClipboard(),
            copyURLHTML = '<span id="copyURLHTML" class="k-link" style="padding-right:10px;" title="Copy URL">Copy URL</span>',
            tooltip = undefined,
            clipTooltip = undefined,
            isError = false;

        client.on('ready', function (e) {
            tooltip = $('<div id="clipTooltip" style="display:none"></div>');
            clipTooltip = tooltip.kendoTooltip({
                callout: false,
                position: 'top',
                content: 'URL has been copied to clipboard.',
                show: function () {
                    setTimeout(function () {
                        clipTooltip.hide();
                    }, 1500);
                },
                animation: {
                    close: {
                        effects: "fade:out",
                        duration: 2000
                    }
                }
            }).data("kendoTooltip");
            tooltip.appendTo($('body'));

            client.on('copy', function (e) {
                var target = $(e.target);
                client.setData(target.data('copyDataType'), target.data('copyData'));
                clipTooltip.show(target);
            });
        });

        client.on('error', function (e) {
            isError = true;
            ZeroClipboard.destroy();
        });

        return {
            clip: function (target) {
                if (isError)
                    return;
                client.clip(target);
            },
            unClip: function (target) {
                if (isError)
                    $(target).off('click');
                client.unClip(target);
            },
            // copyDataType : "text/plain" , "text/html" , "application/rtf"
            setData: function (target, copyDataType, copyData) {
                target = $(target);
                target.data('copyDataType', copyDataType).data('copyData', copyData);
                if (isError) {
                    target.off('click').click(function () {
                        window.prompt("Please copy the following URL:", copyData);
                    });
                    return;
                }
                this.clip(target);
            },
            setText: function (target, text) {
                this.setData(target, 'text/plain', text);
            },
            setCopyURL: function (kendowWindow, options_or_url) {
                var defaultOptions = {
                    text: 'Copy URL',
                    url: Workport.LocationManager.getRoot()
                };
                options_or_url = options_or_url ? ((typeof options_or_url == 'string') ? {
                    url: options_or_url
                } : options_or_url) : defaultOptions;
                var _options = $.extend(defaultOptions, options_or_url);
                var copyURL = kendowWindow.wrapper.data('setCopyURL') ? kendowWindow.wrapper.find('#copyURLHTML') : $(copyURLHTML);
                copyURL.prop('title', _options.text).text(_options.text);
                kendowWindow.wrapper.data('setCopyURL', 1);
                this.setText(copyURL, _options.url);
                kendowWindow.wrapper.find('.k-window-actions').prepend(copyURL);
            },
            removeCopyURL: function (kendowWindow) {
                if (kendowWindow.wrapper.data('setCopyURL')) {
                    var copyURL = kendowWindow.wrapper.find('#copyURLHTML');
                    kendowWindow.wrapper.removeData('setCopyURL');
                    this.unClip(copyURL);
                    copyURL.remove();
                }
            }
        }
    }());
});

Workport.base64 = (function(){
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    function encode64(input) {
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;
        do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
                + keyStr.charAt(enc3) + keyStr.charAt(enc4);
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
        } while (i < input.length);
        return output;
    }

    function decode64(input) {
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;
        if (input.length % 4 != 0) {
            return "";
        }
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec(input)) {
            return "";
        }
        do {
            enc1 = keyStr.indexOf(input.charAt(i++));
            enc2 = keyStr.indexOf(input.charAt(i++));
            enc3 = keyStr.indexOf(input.charAt(i++));
            enc4 = keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output += String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output += String.fromCharCode(chr3);
            }
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
        } while (i < input.length);
        return output;
    }
    function utf16to8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for(i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }
    function utf8to16(str) {
        var out, i, len, c;
        var char2, char3;
        out = "";
        len = str.length;
        i = 0;
        while(i < len) {
            c = str.charCodeAt(i++);
            switch(c >> 4) {
                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
                out += str.charAt(i-1);
                break;
                case 12: case 13:
// 110x xxxx 10xx xxxx
                char2 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                break;
                case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
                    char2 = str.charCodeAt(i++);
                    char3 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x0F) << 12) |
                        ((char2 & 0x3F) << 6) |
                        ((char3 & 0x3F) << 0));
                    break;
            }
        }
        return out;
    }
    return {
        decode: function (s) {
            return decode64(s);
        }        ,
        encode: function (s) {
            return encode64(s);
        }
        ,
        utf8to16: function (str) {
            return utf8to16(str);
        },
        utf16to8: function (str) {
            return utf16to8(str);
        }
    };
}());

Workport.Loader = (function () {
    var def_template = '<div class="common_loading_mask center" style=""></div>\
                        <div class="common_loading_conent center" style="z-index:999999;display:none;">\
                        <div class="common_loading_box center"></div>\
                        <div class="common_loading_sub"><center><img id="loading_image" class="common_loading_img" src="imgs/icons/blackLoading.gif" alt=""/><p class="common_loading_text">Loading</p></center>\
                        </div></div>',
        def_options = {
            text: 'Loading',
            textCSS: {
                'color': 'white',
                'z-index': 2,
                'font-size': '12px'
            },
            imgColor: 'white', // 'black' or 'white'
            imgCSS: {},
            position: 'center', // 'up' or 'down' or 'center'
            hasMask: true,
            maskCSS: {
                'width': '100%',
                'height': '100%',
                'z-index': '9999',
                'background-color': 'rgba(0, 0, 0, 0)'
            },
            boxCSS: {
                'z-index': '-1',
                'background-color': 'white',
                'width': '100%',
                'height': '100%',
                'border-radius': '10px',
                'padding': '8px',
                'opacity': 0
            },
            contCSS:{}
        },
        Imagels = {
            'black': 'imgs/icons/blackLoading.gif',
            'white': 'imgs/icons/whiteLoading.gif'
        },
        Positions = {
            center: 'center',
            up: 'up',
            down: 'down'
        };

    return kendo.Class.extend({
        checkBox: function () {
            this._box.toggle(this._options.position == Positions.center);
            this._box.css('background-color', this._options.imgColor == 'black' ? 'white' : 'rgb(80,80,80)');
        },
        init: function (content, option) {
            this.curPosition = 'center';
            this.iShow = false;
            this._cont = content;
            this._cont.find('.common_loading_mask, .common_loading_conent').remove();
            this._temp = this._cont.append($(def_template)).find('.common_loading_conent');
            this._mask = this._cont.find('.common_loading_mask');
            this._box = this._cont.find('.common_loading_box');
            this._options = Object.create(def_options);
            this.setOptions(option);
            this.hide();
        },
        setContent: function (content, options) {
            this._cont = content;
            this._cont.find('.common_loading_mask, .common_loading_conent').remove();
            if (this._temp || this._mask) {
                this._cont.append(this._temp).append(this._mask)
            } else {
                this._temp = this._cont.append($(def_template)).find('.common_loading_conent');
                this._mask = this._cont.find('.common_loading_mask');
                this._box = this._cont.find('.common_loading_box');
            }
            this.setOptions(options);
            this.hide();
            return this;
        },
        setOptions: function (options) {
            this._options = $.extend(true, {}, def_options, options);
            this._temp.removeAttr('style').css(this._options.contCSS).css({'z-index':99999, 'display':'none'});
            this._temp.find('.common_loading_text').removeAttr('style').css(this._options.textCSS).text(this._options.text);
            this._options.position = Positions[this._options.position] || Positions.center;
            this._temp.find('.common_loading_img').removeAttr('style').css(this._options.imgCSS).prop('src', Imagels[this._options.imgColor] || Imagels.black);
            this._mask.removeAttr('style').css(this._options.maskCSS);
            this._box.removeAttr('style').css(this._options.boxCSS);
            //this.checkBox();
            this.setPosition();
            return this;
        },
        setPosition: function (position) {
            this._options.position = Positions[position] || this._options.position;
            this._temp.removeClass(this.curPosition).addClass(this.curPosition = Positions[this._options.position]);
            //this.checkBox();
            return this;
        },
        show: function () {
            this.iShow = true;
            $(':focus').each(function(){this.blur();});
            if (this._temp) {
                this._temp.show();
            }
            if (this._mask && this._options.hasMask) {
                this._mask.show();
            } else {
                this._mask.hide();
            }
            return this;
        },
        hide: function () {
            this.iShow = false;
            if (this._temp) this._temp.hide();
            if (this._mask) this._mask.hide();
            return this;
        },
        remove: function () {
            this._temp.remove();
            this._temp = null;
            return this;
        },
        wrapper:function(){
            return this._cont;
        },
        reset: function () {
            this.setOptions(Object.create(def_options));
            return this;
        }
    });
}());

Workport.getBrowser = (function () {
    var fBrowserRedirect = function () {
        var sUserAgent = navigator.userAgent.toLowerCase();
        var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
        var bIsChrome = sUserAgent.match(/chrome/i) == "chrome";
        var bIsSafari = sUserAgent.match(/safari/i) == "safari";
        var bIsFirefox = sUserAgent.match(/firefox/i) == "firefox";
        var bIsIE6 = sUserAgent.match(/MSIE\s+6.0/i) == "msie 6.0";
        var bIsIE7 = sUserAgent.match(/MSIE\s+7.0/i) == "msie 7.0";
        var bIsIE8 = sUserAgent.match(/MSIE\s+8.0/i) == "msie 8.0";
        var bIsIE9 = sUserAgent.match(/MSIE\s+9.0/i) == "msie 9.0";
        var bIsIE10 = sUserAgent.match(/MSIE\s+10.0/i) == "msie 10.0";
        var bIsIE11 = sUserAgent.match(/Trident\/7.0/i) == "trident/7.0";
        var useragent = '';
        if (bIsIpad) {
            return 'ipad';
        } else if (bIsChrome) {
            return 'chrome';
        } else if (bIsFirefox) {
            return 'firefox';
        } else if (bIsIE6) {
            return 'IE 6';
        } else if (bIsIE7) {
            return 'IE 7';
        } else if (bIsIE8) {
            return 'IE 8';
        }else if (bIsIE9) {
            return 'IE 9';
        } else if (bIsIE10) {
            return 'ie10';
        } else if (bIsIE11) {
            return 'ie11';
        }else if (bIsSafari) {
            if (sUserAgent.match(/mac\s+os/i)) {
                return 'safari_mac'
            } else {
                return 'safari_windows'
            }
        }
        return useragent
    };
    var ub = fBrowserRedirect();

    return function () {
        return ub;
    }
})();

function onDefaultThumbnailWanted(element, type) {
    if (element == undefined) {
        return;
    }
    if (type == 'c') {
        $(element).attr('src', 'imgs/CommunityDefault.png');
    }
    else if (type == 'C40'){
        $(element).attr('src', 'imgs/community40.png');
    }
    else if (type == 'u') {
        $(element).attr('src', 'imgs/UserDefault.png');
    }
    else if (type == 'U20') {
        $(element).attr('src', 'imgs/20x20.png');
    }
    else if (type == 'U'){
        $(element).attr('src', 'imgs/40.png');
    }else if (type == 'i' || type == 'I') {
        $(element).attr('src', 'imgs/img20.png');
    } else {
        console.log('onDefaultThumbnailWanted: wrong notification type:' + type);
    }

}
function clientonload(){
    Workport.Google.init();
}
function getHttpCodeStatus(httpCode){
    var isError = false;
    if(httpCode.status == 408 || httpCode.status == 0 || httpCode.status == 500){
        isError = true;
    }
    return isError;
}

Workport.Google = (function () {
    var handles = [],
        authResult = undefined,
        auth_ing = false,
        client_id = CLIENT_ID,
        apikey = API_KEY,
        scopes = SCOPES,
        contacts = undefined,
        getingContact = false,
        contactHandlers = [],
        debug = false,
        _inited_ = false;
        _log = function (msg) { if (debug) console.log(msg) },
        _dir = function (obj) { if (debug) console.dir(obj) };

    return {
        init: function () {
            if (!gapi) return;
            gapi.client.setApiKey(apikey);
            _inited_ = true;
        },
        isInited:function(){
            return _inited_;
        },
        getApiKey: function () {
            return apikey;
        },
        fastAuthorize:function(callback){
            this._authorize_(true,function(result){
                callback(result);
            });
        },
        _authorize_:function(immediate, callback){
            if (!gapi || !gapi.auth ) return;
            gapi.auth.authorize({
                client_id: client_id,
                scope: scopes,
                immediate: immediate
            }, function(result){
                authResult = result;
                callback(result);
            });
        },
        authorize:function (immediate, callback) {
            this._authorize_(immediate, function(result){
                for (var i = 0, l = handles.length; i < l; i++) {
                    handles[i](result);
                }
            });
        },
        checkAuth: function (callback) {
            _log('call check auth');
            handles.push(callback);
            if(authResult){
                callback(authResult);
            }else{
                if(!auth_ing){
                    auth_ing = true;

                    var tt = setTimeout(function(){
                        var result = {code:-1,error:{message:'Service Unavailable'}};
                        for (var i = 0, l = handles.length; i < l; i++) {
                            handles[i](result);
                        }
                    },60000);

                    this._authorize_(true,function(result){
                        clearTimeout(tt);
                        for (var i = 0, l = handles.length; i < l; i++) {
                            handles[i](result);
                        }
                        auth_ing = false;
                    });
                }
            }
        },
        getAuthResult: function () {
            return authResult;
        },
        load: function (api, version, callback) {
            if (!gapi) return;
            gapi.client.load(api, version).then(callback);
        },
        getGoogleContacts:function(callback) {
            if(contacts){
                callback(contacts);
                return;
            }
            if(getingContact){
                contactHandlers.push(callback);
                return;
            }
            getingContact = true;
            this._getContacts(function(data){
                for(var i=0,l=contactHandlers.length;i<l;i++){
                    //parse data
                    contactHandlers[i](data);
                }
            });
        },
        _getContacts:function(callback){
            $.ajax({
                url: 'https://www.google.com/m8/feeds/contacts/default/full',
                dataType: "jsonp",
                data: {'alt':'json','access_token': authResult.access_token,'max-results':99999},
                success:function(data) {
                    _log(data);
                    callback(data);
                }
            });
        },
        _getContact:function(contactId, callback){
            //https://www.google.com/m8/feeds/contacts/{userEmail}/full/{contactId}
            $.ajax({
                url: contactId,
                dataType: "jsonp",
                data: {'alt':'json','access_token': authResult.access_token},
                success:function(data) {
                    callback(data);
                }
             });
        }
    }
}());